const {Script} = require("vm");
const {browser} = require('../../');
const jsdom = require('sdenv-jsdom');
const logger = require("../../utils/logger");
const {jsdomFromTextWithCookie, getFile} = require("./index");
const {CookieJar} = jsdom;
const path = require("path");

function func_boss(url, htmltext, jstext, cookie_obj, res, startTime) {
    const url_obj = new URL(url);
    const baseUrl = url_obj.protocol + '//' + url_obj.hostname;
    let defaultCookieJar = new CookieJar();
    let cookie_str = '';
    Object.keys(cookie_obj).forEach(key => {
        cookie_str += `${key}=${cookie_obj[key]}; `
    });
    if (cookie_str) {
        // defaultCookieJar.setCookieSync(cookie_str, baseUrl);
    }
    const [jsdomer, cookieJar] = jsdomFromTextWithCookie({
        url: `${url}`,
        referrer: `${url}`,
        contentType: "text/html",
        runScripts: "outside-only",
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
        parseOptions: {
            sourceCodeLocationInfo: true
        }
    }, defaultCookieJar);
    const dom = jsdomer(htmltext);
    window = dom.window;
    window.onbeforeunload = async (url) => {
        const cookies_str = window.document.cookie;
        let cookies = cookies_str.split('; ').reduce((acc, cur) => {
            const [key, value] = cur.split('=');
            acc[key] = value;
            return acc;
        }, {});
        logger.info(`生成cookie(${new Date().getTime() - startTime}ms):`, cookies);
        window.close();
        if (res) {
            res.status(200).json({
                "code": 200,
                "data": cookies,
                "cost": `${new Date().getTime() - startTime}ms`,
                "msg": "调用成功"
            })
        }
    };
    browser(window, 'chrome');
    new Script(jstext).runInContext(dom.getInternalVMContext());
};


module.exports = func_boss;

// func_boss(
//     'https://www.zhipin.com/web/common/security-check.html?seed=40C9lC9iBzYOlNMN4MHeW4JLEbZEO6iFGBK41kfUbcg%3D&name=a14d4616&ts=1718681103949&callbackUrl=%2Fgongsi%2F%3Fka%3Dheader_brand&srcReferer=',
//     getFile(path.resolve(__dirname, 'boss_index.html')),
//     getFile(path.resolve(__dirname, 'boss_js.js')),
//     {}
// )